package cn.lzj.controller.User;

import cn.lzj.Utils.ReturnInfoUtils;
import cn.lzj.Utils.TimeUtils;
import cn.lzj.controller.base.indexController;
import cn.lzj.pojo.*;
import cn.lzj.service.User.PayTableService;
import cn.lzj.service.User.ProductService;
import cn.lzj.service.User.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.bouncycastle.math.raw.Mod;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;


@Controller
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private ProductService productService;

    @Resource
    private PayTableService payTableService;

    @Resource
    private cn.lzj.controller.base.indexController indexController;

    //取消订单跳转
    @GetMapping("/CancelOrder/{payId}")
    public String CancelOrderController(@PathVariable("payId") Integer payId,HttpServletRequest request,Model model){

        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        PayTable payTableItem = payTableService.getPayTableById(payId);
        userService.CancelOrder(payTableItem);
        return indexController.getProductByPage(1, user.userId,
                "" ,"","","",model,request);
    }

    @GetMapping("/orderDetail/{payId}")
    public String orderDetail(@PathVariable("payId") Integer payId){
        return "";
    }


    //确认收到订单
    @GetMapping("/PayOrder/{payId}")
    public String PayOrderController(@PathVariable("payId") Integer payId, HttpServletRequest request, Model model){

        HttpSession session = request.getSession();
        User user = (User)session.getAttribute("user");
        PayTable payTableItem = userService.getPayTableItemById(payId);
        payTableItem.setPayStatus(1);
        userService.PayOrder(payTableItem);

        return indexController.getProductByPage(1, user.userId,
                "" ,"","","",model,request);
    }

    //收藏信息的搜索功能---实现模糊查询
    @GetMapping("/collect")
    public String collect(String collectSearch, Model model,HttpServletRequest request){
        HttpSession session = request.getSession();
        if(collectSearch == null){
            collectSearch = "";
        }
        User user = (User) session.getAttribute("user");
        return indexController.getProductByPage(1, user.userId,
                "" ,collectSearch,"","",model,request);
    }


    //订单详情的搜索功能---实现模糊查询
    @GetMapping("/order")
    public String order(String orderSearch,Model model,HttpServletRequest request ){
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        if (orderSearch == null){
            orderSearch = "";
        }
        return indexController.getProductByPage(1, user.userId,
                "","",orderSearch,"" ,model,request);
    }



    //历史记录的搜索功能---实现模糊查询
    @GetMapping("/history")
    public String history(HttpServletRequest request, String history,Model model){
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        if(history == null){
            history = "";
        }
        return indexController.getProductByPage(1, user.userId,
                "" ,"","",history,model,request);
    }


//    ====================================已完成===============================================

    //入驻商城
    @PostMapping("/joinLW")
    public String joinLW(String proName,String userName,String addr,String phone,Model model,HttpServletRequest request){
        HttpSession session = request.getSession();
        User user = (User)session.getAttribute("user");
        boolean success = userService.joinLW(proName,userName,addr,phone);

        return indexController.getProductByPage(1, user.userId,
                "" ,"","","",model,request);
    }



    @PostMapping("/evaluateProduct/{proId}")
    public String EvaluateProductController(String text,@PathVariable("proId") Integer proId,
                                            HttpServletRequest request,
                                            Model model
    ){
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        ProductBase product = productService.getProductById(proId);
        Evaluate evaluate = new Evaluate();
        evaluate.setEvaluateContext(text);
        evaluate.setUser(user);
        evaluate.setEvaluateDate(new Date());
        evaluate.setProduct(product);

        userService.EvaluateProduct(evaluate);
        return selectDetailProduct(proId,model,request);
    }

    //获取商品的详细信息

    /**
     * 每次去查看商品的时候，历史记录也会自动添加一行
     * @param productId
     * @param model
     * @param request
     * @return
     */
    @GetMapping("/shoppingInfo/{productId}")
    public String selectDetailProduct(@PathVariable("productId") Integer productId,
                                      Model model,
                                      HttpServletRequest request
    ){
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        Map<ProductBase, List<Evaluate>> productDetail = userService.selectDetailProduct(productId);
        ProductBase productBase = null;
        List<Evaluate> evaluateList = null;
        for (Map.Entry<ProductBase, List<Evaluate>> productBaseListEntry : productDetail.entrySet()) {
            productBase = productBaseListEntry.getKey();
            evaluateList = productBaseListEntry.getValue();
        }
        userService.addHistory(user, productBase);


        model.addAttribute("evaluateList",evaluateList);
        model.addAttribute("productBase", productBase);

        return "shoppingInfo";
    }

    //购买商品
    /*
    js文件的请求："/shoppingInfoPurchase"+"/"+userId+"/"+proId+"/"+price;
    得出，@GetMapping和js文件所填写的请求可以不一致
     */
    @GetMapping("/shoppingInfoPurchase/{productId}")
    public String shoppingInfoPurchase(@PathVariable("productId") Integer productId,
                                       Model model,
                                       HttpServletRequest request
    ){
        HttpSession session = request.getSession();
        User user = (User)session.getAttribute("user");
        ProductBase productBase = productService.getProductById(productId);


        PayTable payTable = new PayTable();
        Date now = new Date();
        int year = now.getYear();
        int month = now.getMonth();
        int day = now.getDay();
        int hour = now.getHours();
        int min = now.getMinutes();
        int sec = now.getSeconds();

        payTable.setPayNo(UUID.randomUUID().toString()+"_"+year+month+day+hour+min+sec);
        payTable.setPayTotalPrice(productBase.getProductPrice());
        payTable.setPayDate(now);
        payTable.setOrderUser(user);
        //0 表示已经支付，但是未送到用户手中  1 表示用户已经收到了商品---“点击了确认收到按钮”
        payTable.setPayStatus(0);
        //生成购买表记录----此时状态为“用户未确认收到”

        Order order = new Order();
        order.setPrice(productBase.getProductPrice());
        order.setOrderNum(1);
        order.setProductBase(productBase);

        boolean success = userService.Shopping(payTable,order);

        productBase.setSellNum(productBase.getSellNum()+1);//销量加1
        productBase.setProductCount(productBase.getProductCount()-1);//库存减1

        productService.updateProduct(productBase);

        return ReturnInfoUtils.returnInfo(success);
    }

    //收藏商品
    @GetMapping("/shoppingInfoCollect/{productId}")
    public String shoppingInfoCollect(@PathVariable("productId") Integer productId,
                                       Model model,
                                      HttpServletRequest request
    ){
        HttpSession session = request.getSession();
        User user = ((User)session.getAttribute("user"));
        //生成收藏记录
        boolean collect = userService.createCollect(user.getUserId(), productId);
        return selectDetailProduct(productId,model,request);
    }
}
